/*
 * @Author: mjxjn@vip.qq.com
 * @Date: 2024-03-09 22:30:48
 * @LastEditors: mjxjn mjxjn@vip.qq.com
 * @LastEditTime: 2024-03-11 23:06:11
 * @FilePath: /Demo/assets/Scripts/Scene/BattleManager.ts
 * @ApiFoxID: 
 * @Description: 
 */
import { _decorator, Component, Node } from 'cc';
import { TileMapManager } from '../Tile/TileMapManager';
import { TILE_HEIGHT, TILE_WIDTH } from '../Tile/TileManager';
import { createUINode } from '../../Utils';
import Levels, {ILevel} from '../../Levels';
import DataManager from '../../Runtime/DataManager';
import EvenetManager from '../../Runtime/EventManager';
import { EVENT_ENUM } from '../../Enum';
import { PlayerManager } from '../Player/PlayerManager';
const { ccclass, property } = _decorator;

@ccclass('BattleManager')
export class BattleManager extends Component {
    level: ILevel
    stage: Node
    start() {
        this.generateStage()
        this.initLevel()
    }

    update(deltaTime: number) {
        
    }

    protected onLoad(): void {
        EvenetManager.Instance.on(EVENT_ENUM.NEXT_LEVEL, this.netxLevel, this)
    }

    protected onDestroy(): void {
        EvenetManager.Instance.off(EVENT_ENUM.NEXT_LEVEL, this.netxLevel)
    }

    initLevel() {
        const level = Levels[`level${DataManager.Instance.levelIndex}`]
        if(level) {
            this.clearLevel()
            this.level = level

            DataManager.Instance.mapInfo = this.level.mapInfo
            DataManager.Instance.mapRowCount = this.level.mapInfo.length || 0
            DataManager.Instance.mapColumnCount = this.level.mapInfo[0].length || 0

            this.generateTileMap()
            this.generatePlayer()
        }
    }

    netxLevel(){
        DataManager.Instance.levelIndex++
        this.initLevel()
    }

    clearLevel(){
        this.stage.destroyAllChildren()
        DataManager.Instance.reset()
    }

    generateStage() {
        this.stage = createUINode()
        this.stage.setParent(this.node)
    }

    generateTileMap() {
        const tileMap = createUINode()
        tileMap.setParent(this.stage)
        const tileMapManager = tileMap.addComponent(TileMapManager)
        tileMapManager.init()

        this.adaptPos()
    }

    generatePlayer() {
        const player = createUINode()
        player.setParent(this.stage)
        const playerManager = player.addComponent(PlayerManager)
        playerManager.init()
    }

    adaptPos() {
        const { mapRowCount, mapColumnCount } = DataManager.Instance
        const disX = TILE_WIDTH * mapRowCount / 2 
        const disY = TILE_HEIGHT * mapColumnCount / 2 + 120
        this.stage.setPosition(-disX, disY)
    }
}

